﻿using System;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;


namespace PartsTracker
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string dbFilePath = string.Empty;


        public MainWindow()
        {
            InitializeComponent();

            System.Windows.Forms.MessageBox.Show("Choose your database file.");

            BrowseToDBFile();

            // Create the tables if this is a new DB
            using (SQLiteConnection db = new SQLiteConnection(dbFilePath))
            {
                db.CreateTable<Part>();
                db.CreateTable<PartHistory>();
            }

            PopulateList();
            PopulateToolComboBox();
        }


        private void PopulateList()
        {
            this.PartListBox.Items.Clear();

            using (SQLiteConnection db = new SQLiteConnection(dbFilePath))
            {
                var parts = db.Query<Part>("select * from part");
                foreach (var part in parts)
                {
                    this.PartListBox.Items.Add(part);
                }
            }
        }


        private void PartListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            EnableBottomForm(false);
            Refresh();
        }

        private void Refresh()
        {
            var part = this.PartListBox.SelectedItem as Part;
            this.PartHistory.Items.Clear();
            EnableTopForm(false);

            if (part != null)
            {
                using (SQLiteConnection db = new SQLiteConnection(dbFilePath))
                {
                    var selected = db.Query<Part>("select * from part where partname = '" + part.PartName + "'").FirstOrDefault();

                    this.SerialNumberTextBox.Text = selected.PartName;
                    this.HoursTextBox.Text = selected.TotalHours.ToString();
                    this.ToolTextBox.Text = selected.Tool;

                    var history = db.Query<PartHistory>("select * from parthistory where partname = '" + part.PartName + "'")
                        .OrderByDescending(x => x.DateModified);

                    foreach (var hist in history)
                    {
                        this.PartHistory.Items.Add(hist);
                    }
                }

            }
        }

        private void BrowseToDBFile()
        {
            Stream stream = null;
            OpenFileDialog dialog = new OpenFileDialog();
            // TODO filter to 'sqlite' files

            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    if ((stream = dialog.OpenFile()) != null)
                    {
                        using (stream)
                        {
                            dbFilePath = ((FileStream)stream).Name;
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox
                        .Show("Error: Could not read file from disk. Original error: " +
                        ex.Message);
                }
            }
        }

        private void PopulateToolComboBox()
        {
            using (SQLiteConnection db = new SQLiteConnection(dbFilePath))
            {
                var toolList = db.Query<Part>("select * from part").Select(x => x.Tool).Distinct();
                this.ToolComboBox.ItemsSource = toolList;
            }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            var selectedPart = this.PartListBox.SelectedItem as Part;

            using (SQLiteConnection db = new SQLiteConnection(dbFilePath))
            {
                if (selectedPart != null)
                {
                    var originalRecord = db.Query<Part>("select * from part where partname = '" + selectedPart.PartName + "'");
                    db.Delete<Part>(originalRecord[0]);
                }

                if (!string.IsNullOrWhiteSpace(this.ToolTextBox.Text) &&
                    !string.IsNullOrWhiteSpace(this.SerialNumberTextBox.Text) &&
                    !string.IsNullOrWhiteSpace(this.HoursTextBox.Text) &&
                    this.HoursTextBox.Text.All(x => char.IsNumber(x)))
                {
                    db.Insert(new Part
                    {
                        Tool = this.ToolTextBox.Text,
                        PartName = this.SerialNumberTextBox.Text,
                        TotalHours = Convert.ToInt32(this.HoursTextBox.Text)
                    });
                }

            }

            PopulateList();

            EnableTopForm(false);
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            this.PartListBox.SelectedItem = null;
            EnableTopForm(true);

            this.HoursTextBox.Text = string.Empty;
            this.SerialNumberTextBox.Text = string.Empty;
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            EnableBottomForm(true);
        }


        private void EnableTopForm(bool isEnabled)
        {
            this.ToolTextBox.IsEnabled = isEnabled;
            this.HoursTextBox.IsEnabled = isEnabled;
            this.SerialNumberTextBox.IsEnabled = isEnabled;
        }

        private void EnableBottomForm(bool isEnabled)
        {
            this.HoursEnteredTextBox.IsEnabled = isEnabled;
            this.CommentTextBox.IsEnabled = isEnabled;
            this.DateTimePicker.IsEnabled = isEnabled;

            this.SaveRecordButton.IsEnabled = isEnabled;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            EnableBottomForm(false);

            var hoursText = this.HoursEnteredTextBox.Text;
            var commentText = this.CommentTextBox.Text;
            var selectedDate = this.DateTimePicker.SelectedDate;

            if (hoursText.All(x => char.IsNumber(x)) && selectedDate.HasValue)
            {
                using (SQLiteConnection db = new SQLiteConnection(dbFilePath))
                {
                    db.Insert(new PartHistory
                    {
                        Comment = commentText,
                        HoursEntered = Convert.ToInt32(hoursText),
                        DateModified = DateTime.Now,
                        Date = selectedDate.Value,
                        ModifiedBy = WindowsIdentity.GetCurrent().Name,
                        PartName = ((Part)this.PartListBox.SelectedItem).PartName
                    });

                    var totalHours = db.Query<PartHistory>("Select * from parthistory where partname = '" +
                        ((Part)this.PartListBox.SelectedItem).PartName + "'")
                        .Sum(x => x.HoursEntered);

                    var updatedPart = db.Query<Part>("Select * from part where partname = '" +
                        ((Part)this.PartListBox.SelectedItem).PartName + "'").First();

                    updatedPart.TotalHours = totalHours;

                    db.Update(updatedPart);
                }
            }



            Refresh();

        }

        private void TextBox_TextChanged_1(object sender, TextChangedEventArgs e)
        {
            var text = this.SearchTextBox.Text;
            if (text == "Start typing to search") return;

            using (SQLiteConnection db = new SQLiteConnection(dbFilePath))
            {
                var parts = db.Query<Part>("select * from part").Where(x => x.PartName.StartsWith(text));
                this.PartListBox.Items.Clear();

                foreach (var part in parts)
                {
                    this.PartListBox.Items.Add(part);
                }
            }
        }

        private void PartHistory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedHistory = this.PartHistory.SelectedItem as PartHistory;

            if (selectedHistory != null)
            {
                this.HoursEnteredTextBox.Text = selectedHistory.HoursEntered.ToString();
                this.CommentTextBox.Text = selectedHistory.Comment;
                this.DateTimePicker.SelectedDate = selectedHistory.Date;

            }
        }

        private void ToolComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            if (e.AddedItems.Count == 1 && !string.IsNullOrWhiteSpace(e.AddedItems[0] as string))
            {
                var selectedTool = e.AddedItems[0] as string;

                // Filter list to only parts for this tool
                using (SQLiteConnection db = new SQLiteConnection(dbFilePath))
                {
                    var filteredPartList = db.Query<Part>(string.Format("select * from part where tool = '{0}'", selectedTool));

                    this.PartListBox.Items.Clear();
                    foreach (var part in filteredPartList)
                    {
                        this.PartListBox.Items.Add(part);
                    }
                }
            }

        }

        private void SearchTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            // Clear the text once they focus the search
            if (this.SearchTextBox.Text.ToLower() == "start typing to search")
            {
                this.SearchTextBox.Text = string.Empty;
            }

            this.ToolComboBox.SelectedItem = null;
        }




    }
}
